package com.gugee.ins.common.dal.service.media.impl;


import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.gugee.ins.common.dal.mapper.media.InsRelMediaSponsorUserMapper;
import com.gugee.ins.common.dal.service.media.InsRelMediaSponsorUserDao;
import com.gugee.ins.common.model.mysql.media.InsRelMediaSponsorUser;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;

/**
 * InsRelMediaSponsorUserDaoImpl dao
 * @author Huangxin
 */
@Slf4j
@Service
public class InsRelMediaSponsorUserDaoImpl extends ServiceImpl<InsRelMediaSponsorUserMapper, InsRelMediaSponsorUser>
        implements InsRelMediaSponsorUserDao {
    /**
     * 批量插入
     * @param shortcode
     * @param uid
     * @param sponsoredUid
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void batchInsert(String shortcode,long takenTime,long uid,List<Long> sponsoredUid) {
        if(!sponsoredUid.isEmpty()){
            long now = System.currentTimeMillis() / 1000;
            List<InsRelMediaSponsorUser> insRelMediaSponsorUsers = new ArrayList<>(sponsoredUid.size());
            for(long sponsorUid : sponsoredUid){
                InsRelMediaSponsorUser insRelMediaSponsorUser = new InsRelMediaSponsorUser();
                insRelMediaSponsorUser.setCreateTime(now);
                insRelMediaSponsorUser.setShortcode(shortcode);
                insRelMediaSponsorUser.setSponsorUid(sponsorUid);
                insRelMediaSponsorUser.setUid(uid);
                insRelMediaSponsorUser.setTakenTime(takenTime);
                insRelMediaSponsorUsers.add(insRelMediaSponsorUser);
            }
            try{
                this.saveBatch(insRelMediaSponsorUsers);
            }catch (Exception e){
                log.debug("batch insert ins rel media sponsored user failed ,try insert one by one, msg : {} ",e.getMessage());
                insRelMediaSponsorUsers.forEach(insRelMediaSponsorUser -> {
                    try{
                        baseMapper.insert(insRelMediaSponsorUser);
                    }catch (Exception ex){
                        log.info("insert ins rel media tagger user failed ,uid : {} ,shortcode : {},taggerUid : {}, msg : {} "
                                ,insRelMediaSponsorUser.getUid(),insRelMediaSponsorUser.getShortcode()
                                ,insRelMediaSponsorUser.getSponsorUid(),ex.getMessage());
                    }
                });
            }
        }
    }

}
